//
//  JSPhotoPickerAssetSelectViewController.m
//  JSPhotoPicker
//
//  Created by JasonLee on 2018/8/13.
//  Copyright © 2018年 JasonLee. All rights reserved.
//

#import "JSPhotoPickerAssetSelectViewController.h"
#import "JSPhotoPickerAssetsCollectionViewCell.h"
#import "JSPhotoBrowsViewController.h"
#import "JSPhotoPickerDatas.h"
#import "JSPhotoPickerCommon.h"
static CGFloat CELL_ROW = 4;
static CGFloat CELL_MARGIN = 2;
static CGFloat CELL_LINE_MARGIN = 2;
static NSInteger PHOTO_DEFAULT_SHOW_MAX_COUNT = 9;
static CGFloat TOOLBAR_HEIGHT = 44;
@interface JSPhotoPickerAssetSelectViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,JSPhotoPickerAssetsCollectionViewCellDelegate>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *datasourceArray;
@property(nonatomic,strong)NSMutableArray *selectedAssetArray;
//@property(nonatomic,strong)NSMutableArray *selectedImageArray;

@property (strong,nonatomic) UIButton *doneBtn;
@property (strong,nonatomic) UIToolbar *toolBar;
@property (strong,nonatomic) UILabel *makeView;
@end

@implementation JSPhotoPickerAssetSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.group.groupName;
    [self.view addSubview:self.collectionView];
    [self setupToorBar];
    typeof(self)weakSelf = self;
    [[JSPhotoPickerDatas defaultPicker] getAllPhotosWithGroup:self.group andPhotos:(self.status == PickerViewShowStatusCameraRoll? YES : NO) andFinished:^(id objc) {
        [weakSelf.datasourceArray addObjectsFromArray:objc];
        [weakSelf.collectionView reloadData];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.collectionView reloadData];
    [self updateMakeViewStatus:self.selectedAssetArray.count];
}
-(UICollectionView *)collectionView{
    if (!_collectionView) {
        CGFloat cellW = (self.view.frame.size.width - CELL_MARGIN * CELL_ROW + 1) / CELL_ROW;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(cellW, cellW);
        layout.minimumLineSpacing = CELL_LINE_MARGIN;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-TOOLBAR_HEIGHT) collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[JSPhotoPickerAssetsCollectionViewCell class] forCellWithReuseIdentifier:@"JSPhotoPickerAssetsCollectionViewCell"];
    }
    return _collectionView;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datasourceArray.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    JSPhotoPickerAssetsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"JSPhotoPickerAssetsCollectionViewCell" forIndexPath:indexPath];
    cell.delegate = self;
    PHAsset *asset;
    if (indexPath.row < self.datasourceArray.count) {
        asset = self.datasourceArray[indexPath.row];
    }
//    cell.asset = asset;
    [cell updateCellWithPHAsset:asset andSelected:[self.selectedAssetArray containsObject:asset]];
    return cell;
}

-(void)js_photoPickerCollectionImageViewTapAction:(UIImageView *)imageView andPHAsset:(PHAsset *)asset{
    NSLog(@"去查看大图");
    JSPhotoBrowsViewController *browsVC = [JSPhotoBrowsViewController new];
    browsVC.assetArray = self.datasourceArray;
    browsVC.selectedAssetArray = self.selectedAssetArray;
    browsVC.currentIndex = [self.datasourceArray indexOfObject:asset];
    browsVC.maxCount = self.maxCount;
    [self.navigationController pushViewController:browsVC animated:YES];
}
-(void)js_photoPickerCollectionSelectedAction:(UIButton *)selectButton andPHAsset:(PHAsset *)asset{
    NSInteger maxCount = (self.maxCount <= 0) ? PHOTO_DEFAULT_SHOW_MAX_COUNT :self.maxCount;
    selectButton.selected = !selectButton.selected;
    if (selectButton.selected && ![self.selectedAssetArray containsObject:asset]) {
        if (self.selectedAssetArray.count < maxCount) {
            [self.selectedAssetArray addObject:asset];
        }else{
            selectButton.selected = !selectButton.selected;
            NSString *alertStr = [NSString stringWithFormat:@"最多只能选择%ld张图片",(long)maxCount];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:alertStr delegate:self cancelButtonTitle:nil otherButtonTitles:@"好的", nil];
            [alertView show];
            return ;
        }
        
    }else{
        [self.selectedAssetArray removeObject:asset];
    }
    [self updateMakeViewStatus:self.selectedAssetArray.count];
    self.doneBtn.enabled = self.selectedAssetArray.count != 0;
    NSLog(@"%@图片",selectButton.selected ? @"选中了":@"取消了");
    NSLog(@"%lu",(unsigned long)self.selectedAssetArray.count);
}
-(void)updateMakeViewStatus:(NSInteger)count{
    self.makeView.text = [NSString stringWithFormat:@"%ld",(long)self.selectedAssetArray.count];
    self.makeView.hidden = !count;
}
- (void) done{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:PICKER_TAKE_DONE object:nil userInfo:@{@"selectAssets":self.selectedAssetArray}];
    });
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) setupToorBar{
    UIToolbar *toorBar = [[UIToolbar alloc] init];
    toorBar.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:toorBar];
    self.toolBar = toorBar;
    
    NSDictionary *views = NSDictionaryOfVariableBindings(toorBar);
    NSString *widthVfl =  @"H:|-0-[toorBar]-0-|";
    NSString *heightVfl = @"V:[toorBar(44)]-0-|";
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:widthVfl options:0 metrics:0 views:views]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:heightVfl options:0 metrics:0 views:views]];
    
    // 左视图 中间距 右视图
    //    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:self.previewBtn];
    UIBarButtonItem *fiexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:self.doneBtn];
    self.doneBtn.enabled = NO;
    toorBar.items = @[fiexItem,rightItem];
    
}
- (UIButton *)doneBtn{
    if (!_doneBtn) {
        _doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_doneBtn setTitleColor:[UIColor colorWithRed:0/255.0 green:91/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
        [_doneBtn setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
        
        _doneBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _doneBtn.frame = CGRectMake(0, 0, 45, 45);
        [_doneBtn setTitle:@"完成" forState:UIControlStateNormal];
        [_doneBtn addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
        [_doneBtn addSubview:self.makeView];
        
    }
    return _doneBtn;
}
- (UILabel *)makeView{
    if (!_makeView) {
        UILabel *makeView = [[UILabel alloc] init];
        makeView.textColor = [UIColor whiteColor];
        makeView.textAlignment = NSTextAlignmentCenter;
        makeView.font = [UIFont systemFontOfSize:13];
        makeView.frame = CGRectMake(25, -5, 20, 20);
        makeView.hidden = YES;
        makeView.layer.cornerRadius = makeView.frame.size.height / 2.0;
        makeView.clipsToBounds = YES;
        makeView.backgroundColor = [UIColor redColor];
        [self.view addSubview:makeView];
        self.makeView = makeView;
        
    }
    return _makeView;
}
-(NSMutableArray *)datasourceArray{
    if (!_datasourceArray) {
        _datasourceArray = [@[] mutableCopy];
    }
    return _datasourceArray;
}
-(NSMutableArray *)selectedAssetArray{
    if (!_selectedAssetArray) {
        _selectedAssetArray = [@[] mutableCopy];
    }
    return _selectedAssetArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
